// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.android.apps.moderator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

/**
 * The default entry point for the application. Allows the user to select a
 * series to view.
 */
public class MainActivity extends RefreshableActivity {

  private static final String TAG = MainActivity.class.getName();
 
  private ListSynchronizer recentListSynchronizer;
  private ListSynchronizer recommendedListSynchronizer;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    List<Integer> list = new ArrayList<Integer>();
    list.add(R.layout.series_entry_compact);
    list.add(R.layout.topic_entry);
    recentListSynchronizer =
        new ListSynchronizer(this, ((ListView) findViewById(R.id.ListViewRecent)), list);
    recommendedListSynchronizer =
        new ListSynchronizer(this, ((ListView) findViewById(R.id.ListViewRecommended)), list);
    Button button = (Button) findViewById(R.id.GoButton);
    button.setOnClickListener(new OnClickListener(){

      public void onClick(View v) {
        
        String urlText = ((EditText) findViewById(R.id.URL)).getText().toString();
        Intent intent = new Intent(MainActivity.this, MainUrlActivity.class);
        if (urlText.startsWith(getString(R.string.url_base))) {
          intent.setData(Uri.parse(urlText));
          startActivity(intent);
        } else {
          // Final attempt .. try parsing just a hex series ID
          try {
            int seriesId = Integer.parseInt(urlText, 16);
            intent.setData(
                Uri.parse(getString(R.string.series_url_base) + Integer.toHexString(seriesId)));
            startActivity(intent);
          } catch (NumberFormatException ex) {
            alert(R.string.not_a_valid_url);
          }
        }
        
      }});
    refresh();
  }

  @Override
  public void onRestart() {
    refresh();
    super.onRestart();
  }

  @Override
  void refresh() {
    // Recent series
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    Set<Integer> recentSeriesIncluded = new HashSet<Integer>();
    List<ListEntry> recentEntries = new ArrayList<ListEntry>();
    
    String recentJson = preferences.getString(PREFERENCE_KEY_RECENT_SERIES, null);
    if (recentJson != null) {
      try {
        JSONArray array = new JSONArray(recentJson);
        for (int idx = 0; idx != array.length(); idx++) {
          JSONObject obj = array.getJSONObject(idx);
          recentEntries.add(new SeriesListEntry(obj, true));
          // These series are not listed in 'recommended'
          int seriesId = obj.getJSONObject("data").getJSONObject("id").getInt("seriesId");
          recentSeriesIncluded.add(seriesId);
        }
      } catch (JSONException e) {
        Log.i(TAG, "Could not generate list", e);
      }
    }

    View recentlyViewedContainer = findViewById(R.id.RecentlyViewedContainer);
    if (recentEntries.size() > 0) {
      recentListSynchronizer.setEntries(recentEntries);
      recentlyViewedContainer.setVisibility(View.VISIBLE);
    } else {
      recentlyViewedContainer.setVisibility(View.GONE);
    }

    // Recommended series
    List<ListEntry> recommendedEntries = new ArrayList<ListEntry>();
    
    try {
      List<JSONObject> array = new ArrayList<JSONObject>();
      // TODO: remove this hard-wired list when the server component is complete for 'hot' lists
      array.add(new JSONObject().put("data", new JSONObject().put("id", new JSONObject()
          .put("seriesId", 26864)).put("name", "Google I/O Sessions")));
      array.add(new JSONObject().put("data", new JSONObject().put("id", new JSONObject()
          .put("seriesId", 2035)).put("name", "Ask a Google engineer")));
      for (JSONObject obj : array) {
        // Don't include series already listed in 'recents'
        int seriesId = obj.getJSONObject("data").getJSONObject("id").getInt("seriesId");
        if (!recentSeriesIncluded.contains(seriesId)) {
          recommendedEntries.add(new SeriesListEntry(obj, true));
        }
      }
    } catch (JSONException e) {
      Log.i(TAG, "Could not generate list", e);
    }    
    
    View recommendedContainer = findViewById(R.id.RecommendedContainer);
    if (recommendedEntries.size() > 0) {
      recommendedListSynchronizer.setEntries(recommendedEntries);
      recommendedContainer.setVisibility(View.VISIBLE);
    } else {
      recommendedContainer.setVisibility(View.GONE);
    }
  }
}
